<script setup>
import TodoHeader from './components/TodoHeader.vue'
import TodoMain from './components/TodoMain.vue'
import TodoFooter from './components/TodoFooter.vue'
import { ref, watch } from 'vue'

// 先读取本地存储的，本地没有短路准备空数组(防止后面业务调用数组方法报错)
const list = ref(JSON.parse(localStorage.getItem('todo-list')) || [])

// 修改任务状态功能
const changeDoneFn = id => {
  // console.log('父组件接收id', id)
  const todo = list.value.find(v => v.id === id)
  todo.done = !todo.done
}

// 删除功能
const delTodoFn = id => {
  // splice
  // const index = list.value.findIndex(v => v.id === id)
  // list.value.splice(index, 1)

  // filter
  list.value = list.value.filter(v => v.id !== id)
}

// 新增功能
const addTodoFn = val => {
  // 前添加一条数据
  list.value.unshift({
    id: Date.now(),
    content: val,
    done: false,
  })
}

// 修改全选状态
const checkAllFn = bl => {
  // 遍历批量修改
  list.value.forEach(item => {
    item.done = bl
  })
}

// 监听数组变化，把数据同步到本地存储
watch(
  list,
  () => {
    localStorage.setItem('todo-list', JSON.stringify(list.value))
  },
  { deep: true },
)
</script>

<template>
  <section class="todoapp">
    <TodoHeader @add-todo="addTodoFn"></TodoHeader>
    <TodoMain
      :list="list"
      @change-done="changeDoneFn"
      @del-todo="delTodoFn"
      @check-all="checkAllFn"
    ></TodoMain>
    <TodoFooter :list="list"></TodoFooter>
  </section>
</template>

<style></style>
